import {initState} from './state'
import {compileToFunction} from './compiler/index.js'
import {mountComponent, callHook} from './lifecycle.js'

import {mergeOptions} from './util/index'
import {nextTick} from './util/next-tick'
export function initMixin(Vue) {
  Vue.prototype._init = function(options) {
    // 数据劫持
    const vm = this;
    vm.$options = mergeOptions(vm.constructor.options, options);

    callHook(vm, 'beforeCreate')

    // 初始化状态
    initState(vm)

    callHook(vm, 'created')
    // 如果用户传入了el 属性  就要实现挂载流程
    if(vm.$options.el) {
      vm.$mount(vm.$options.el)
    }
  }

  Vue.prototype.$mount = function(el) {
    const vm = this
    const options = vm.$options
    el = document.querySelector(el)
    // 优先级 render > template > el
    if(!options.render) {
      // 对末班进行编译
      let template = options.template
      if(!template && el) {
        template = el.outerHTML
      }
      // console.log(template)
      // 将template 转化成 render 方法
      const render = compileToFunction(template)
      console.log(render)
      options.render = render
    }
    mountComponent(vm, el)
  }
  Vue.prototype.$nextTick = nextTick
}